package com.slmxz.tms.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.slmxz.tms.common.component.RedisUserService;
import com.slmxz.tms.common.constant.SystemConstants;
import com.slmxz.tms.common.enums.BizMessageEnum;
import com.slmxz.tms.common.model.Option;
import com.slmxz.tms.core.exception.Asserts;
import com.slmxz.tms.core.security.util.SecurityUtils;
import com.slmxz.tms.core.service.DataScopeService;
import com.slmxz.tms.system.mapper.CompanyMapper;
import com.slmxz.tms.system.model.vo.UserInfoVO;
import com.slmxz.tms.system.service.CompanyService;
import com.slmxz.tms.common.constant.NumberContants;
import com.slmxz.tms.core.exception.BizException;
import com.slmxz.tms.common.result.ResultCode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.slmxz.tms.system.model.entity.Company;
import com.slmxz.tms.system.model.vo.CompanyVO;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import cn.hutool.core.util.StrUtil;

/**
 * 公司管理服务实现类
 * @author sunyao
 * @Date 2024-11-05
 */
@Service
@RequiredArgsConstructor
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company> implements CompanyService, DataScopeService<Company> {

    /**
    * 获取公司管理分页列表
    * @return {@link IPage<CompanyVO>} 公司管理分页列表
    */
    @Override
    public IPage<CompanyVO> selectCompanyPage(IPage<CompanyVO> page,CompanyVO company) {
        UserInfoVO user = RedisUserService.currentUser();
        try{
            this.dataScopeHandler(company);
        }catch (Exception e){
            company.setScopeNo(user.getScopeNo());
            company.setDataOperate(SystemConstants.OPERATE_EQUALS);
        }
        return page.setRecords(this.baseMapper.selectCompanyPage(page,company));
    }
    
    /**
     * @param id 公司管理ID
     * @return
     */
    @Override
    public CompanyVO selectCompanyDetail(Long id) {
        Company entity = this.getById(id);
        return BeanUtil.copyProperties(entity,CompanyVO.class);
    }
    
    /**
     * 新增公司管理
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveCompany(CompanyVO company) {

        if(company.getParentId() == null){
            company.setScopeNo(getMaxScopeNo(null));
        }else{
           Company parentCompany = this.getById(company.getParentId());
           //父级公司 + 自身的scopeNo
            company.setScopeNo(parentCompany.getScopeNo() + getMaxScopeNo(parentCompany.getScopeNo()));
        }
        return this.save(company);
    }

    private String getMaxScopeNo(String scopeNo) {
        if(scopeNo == null){
            return SystemConstants.MAX_SCOPE_NO;
        }
        //检查是否存在相同的scopeNo
        QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByDesc(Company::getScopeNo)
                .likeRight(StrUtil.isNotBlank(scopeNo), Company::getScopeNo, scopeNo)
                // 字符串类型字段名
                .last("LIMIT 1").select(Company::getScopeNo);
       Company maxScopeCompany = this.getOne(queryWrapper);
       if(maxScopeCompany == null){
           return SystemConstants.MAX_SCOPE_NO;
       }
       long maxScopeNo = Long.parseLong(maxScopeCompany.getScopeNo());
       return String.valueOf(maxScopeNo + NumberContants.NUMBER_1);
    }
    
    /**
     * 更新公司管理
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCompany(CompanyVO company) {
        Asserts.fail(company.getId() == null, BizMessageEnum.PARAM_IS_NULL);
        //查询公司数据是否存在
        Company oldCompany = this.getById(company.getId());
        Asserts.fail(oldCompany == null, BizMessageEnum.PARAM_IS_NULL);
        if(company.getParentId() == null || oldCompany.getParentId().equals(company.getParentId())){
            company.setScopeNo(oldCompany.getScopeNo());
        }else{
            Company parentCompany = this.getById(company.getParentId());
            company.setScopeNo(parentCompany.getScopeNo() + this.getMaxScopeNo(parentCompany.getScopeNo()));
        }
        return this.updateById(company);
    }
    
    /**
     * 删除公司管理
     *
     * @param ids 公司管理ID，多个以英文逗号(,)分割
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteCompanys(String ids) {
        Asserts.fail(StrUtil.isBlank(ids), BizMessageEnum.PARAM_IS_NULL);
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean activeOrLogout(CompanyVO company) {
        //激活或者注销业务数据
        Asserts.fail(CollectionUtil.isEmpty(company.getIds()) || company.getIsDeleted() == null,BizMessageEnum.PARAM_IS_NULL);

        List<Company>  companyList = new ArrayList<>(company.getIds().size());
        company.getIds().forEach(id -> {
            Company companyItem = new Company();
            companyItem.setId(id);
            companyItem.setIsDeleted(company.getIsDeleted());
            companyList.add(companyItem);
        });
        this.updateBatchById(companyList,10);
        return true;
    }

    @Override
    public List<Option<String>> options(CompanyVO company) {
        UserInfoVO user = RedisUserService.currentUser();
        //查询所有公司作为下拉框
        if(!SecurityUtils.isRoot()){
            try{
                this.dataScopeHandler(company);
            }catch (Exception e){
                company.setScopeNo(user.getScopeNo());
                company.setDataOperate(SystemConstants.OPERATE_EQUALS);
            }
        }
        return this.baseMapper.selectOption(company);
    }
}
